package org.manon.json.asm;

import org.manon.json.analyse.ClassRegistry;
import org.manon.json.meta.Entity;
import org.objectweb.asm.ClassWriter;

/**
 * @author <a href="mailto:jacques.militello@gmail.com">Jacques Militello</a>
 */
public final class ASMGenerator {

	public static void buildSerializers(ClassRegistry classRegistry, ASMClassFactory holder) {
		final ASMGenerator4Serializer generator = new ASMGenerator4Serializer(classRegistry);
		
		//1. first pass -> create all class writer.
		for (Entity entity : classRegistry.treeValues()) {
			
			if (entity.getCustomSerializer() != null) {
				generator.getAllClasses().put(entity, null);
				// custom serializer -> skip.
				continue;
			}
			
			final ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
			generator.generateClassHeader(classRegistry,entity, classWriter);
			generator.getAllClasses().put(entity, classWriter);
		}
		
		ClassWriter classWriter;
		//2. second pass -> create header, classField and methods...
		for (Entity entity : generator.getAllClasses().keySet()) {
			
			if (entity.getCustomSerializer() != null) {
				// custom serializer -> skip.
				continue;
			}
			
			classWriter = generator.getAllClasses().get(entity);
			generator.generateBody(entity,classWriter);
			holder.registerSerializer(entity, classWriter.toByteArray());
		}
	}
	
	public static void buildDeSerializers(ClassRegistry classRegistry, ASMClassFactory holder) {
		
		final ASMGenerator4Deserializer generator = new ASMGenerator4Deserializer(classRegistry);
		ClassWriter classWriter;
		
		//1. first pass -> create all class writer.
		for (Entity entity : classRegistry.treeValues()) {
			classWriter = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
			generator.generateClassHeader(entity, classWriter);
			generator.getAllClasses().put(entity, classWriter);
		}
		
		//2. second pass -> create header, classField and methods...
		for (Entity entity : generator.getAllClasses().keySet()) {
			classWriter = generator.getAllClasses().get(entity);
			generator.generateBody(entity,classWriter,holder);
			holder.registerDeserializer(entity, classWriter.toByteArray());
		}
	}
	
}